package com.jse.dao;

import java.io.Serializable;
import com.jse.log.Log;
import com.jse.log.Logs;

public class Pager implements Serializable {

    private static final long serialVersionUID = 8848523495013555357L;

    private static final Log log = Logs.get();

    /**
     * 改变这个，当每页大小超过 MAX_FETCH_SIZE 时，这个将是默认的 fetchSize
     */
    public static int DEFAULT_PAGE_SIZE = 20;

    /**
     * ResultSet 最大的 fetch size
     */
    public static int MAX_FETCH_SIZE = 200;

    // private static final int FIRST_PAGE_NUMBER = 1;

    private int num;
    private int size;
    private int page;
    private int count;

    public Pager() {
        this.num = 1;
        this.size = DEFAULT_PAGE_SIZE;
    }

    public Pager(int num) {
        if (num < 1)
        	num = 1;
        this.num = num;
        this.size = DEFAULT_PAGE_SIZE;
    }

    public Pager(int num, int size) {
        if (num < 1)
        	num = 1;
        if (size < 1)
            size = DEFAULT_PAGE_SIZE;
        this.num = num;
        this.size = size;
    }

    public Pager resetPage() {
    	page = -1;
        return this;
    }

    public int getPage() {
        if (page < 0)
        	page = (int) Math.ceil((double) count / size);
        return page;
    }

    public int getNum() {
        return num;
    }

    public int getSize() {
        return size;
    }

    public int getCount() {
        return count;
    }

    public Pager setPage(int pn) {
        if (1 > pn && log.isInfoEnabled())
            log.infof("num shall start at 1, but input is %d, that mean pager is disable", pn);
        num = pn;
        return this;
    }

    public Pager setSize(int size) {
        this.size = (size > 0 ? size : DEFAULT_PAGE_SIZE);
        return resetPage();
    }

    public Pager setCount(int count) {
        this.count = count > 0 ? count : 0;
        this.page = (int) Math.ceil((double) count / size);
        return this;
    }

    public int getOffset() {
        return size * (num - 1);
    }
    
    @Override
	public String toString() {
		return String.format("{\"num\":%d,\"size\":%d,\"count\":%d,\"page\":%d}",
				(getNum()-1),getSize(),getCount(),getPage());
	}


    public boolean isFirst() {
        return num == 1;
    }

    public boolean isLast() {
        if (page == 0)
            return true;
        return num == page;
    }

    public boolean hasNext() {
        return !isLast();
    }

    public boolean hasPrevious() {
        return !isFirst();
    }
  
	public String toSql() {
		return String.format(" limit %d,%d",getNum()-1,getSize());
	}
}
